package edu.java.ishop.services;

import java.util.Arrays;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import edu.java.ishop.dao.UserDao;
import edu.java.ishop.dao.UserRoleDao;
import edu.java.ishop.model.User;
import edu.java.ishop.model.UserRole;

@Named
public class UserAuthorityService implements UserDetailsService {

	@Inject
	private UserDao userDao;
	
	@Inject
	private UserRoleDao userRoleDao;
	
	public UserAuthorityService(){
		
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
		
		User user = userDao.getByUsername(username);
		
		if(user==null){
			throw new UsernameNotFoundException("User with username: "+username + " does not exist");
		}
		
		UserRole principal = userRoleDao.getByUserId(user.getId());
		
		if(principal == null){
			
			throw new RuntimeException("User does not have any role assigned");
		}
		
		SimpleGrantedAuthority sga = new SimpleGrantedAuthority(principal.getRoleName().name());
		user.setGrantedAuthority(Arrays.asList(sga));
		
		return user;
	}

}
